package com.wuseguang.springcloud.dao.jdbc;

import com.alibaba.fastjson.JSON;
import com.wuseguang.springcloud.JdbcTemplate.BaseTemplate;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.jdbc.core.BatchPreparedStatementSetter;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;

import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.List;
import java.util.Map;

@Repository
public class ClassRollCallJdbc extends BaseTemplate {

    private Logger logger = LoggerFactory.getLogger(this.getClass());


    public int batchAddClassAttend(String list, Integer id, Integer teacherId) {
        try {
            String sql = " UPDATE  class_rollcall SET teacher_id=?,updatetime=now() WHERE id=?";//修改点名教师信息
            updateByParameter(sql, teacherId, id);
            sql = "delete from class_rollcall_student where rollcall_id=?";//先删除该节次学生考勤信息
            updateByParameter(sql, id);
            sql = "insert into `class_rollcall_student` (`rollcall_id`, `student_id`, `opertime`, `type`) values(?,?,now(),?)";//批量添加
            List<Map<String, Object>> parse = (List<Map<String, Object>>) JSON.parse(list);
            return dao.batchUpdate(sql, new BatchPreparedStatementSetter() {
                @Override
                public void setValues(PreparedStatement ps, int i) throws SQLException {
                    Map<String, Object> map = parse.get(i);
                    logger.info("batchAddClassAttend()，节次id={}", id);
                    ps.setObject(1, id);
                    ps.setObject(2, map.get("id"));//学生id
                    ps.setObject(3, map.get("type"));// 0出勤 1缺勤 2 请假 3迟到 4未考勤
                }

                @Override
                public int getBatchSize() {
                    return parse.size();
                }
            }).length;
        } catch (Exception e) {
            logger.info("批量添加异常,error={}", e);
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();// 手动回滚
        }
        return 0;
    }


}
